package com.netpace.iem.umair.dal;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.netpace.iem.umair.model.Label;

public class LabelMemory implements ILabelDao {
	private List<Label> labels;
	Connection conn;
	static Logger log = Logger.getLogger(CategoryMemory.class.getName());

	// Default constructor is for Main memory Db
	public LabelMemory() {
		log.debug("Main Memory DB Selected");
		this.labels = new ArrayList<Label>();
	}
	
	@Override
	public void insert(Label label){
		log.debug("1 record inserted");
		labels.add(label);
	}
	
	@Override
	public void update(Label label, int pk) {
		int index = getIndex(pk);
		if ( index != -1 ) {
			log.debug("1 record updated");
			labels.remove(index);
			labels.add(index, label);
		}
	}
	
	@Override
	public void delete(Label label, int pk) {
		int index = getIndex(label); 
		if ( index != -1 ) {
			log.debug("1 record deleted");
			labels.remove(index);
		}
	}
	
	@Override
	public void delete(int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			log.debug("1 record deleted");
			labels.remove(index);
		}
	}
	
	@Override
	public Label findById(int pk) {
		int index = getIndex(pk); 
		
		if ( index != -1 ) {
			log.debug("returning the record found");
			return labels.get(index);
		}
		
		return null;
	}
	
	@Override
	public List<Label> findAll(){
		log.debug("returning the records found");
		return labels;
	}
	
	private int getIndex(Label label) {
		if ( labels.contains(label) ) 
			return labels.indexOf(label);
		else
			return -1;
	}
	
	private int getIndex(int pk) {
		for (int i = 0; i < labels.size(); i++) {
			if ( labels.get(i).getId() == pk ) {
				return i;
			}
		}
		
		return -1;
	}
}
